<template>
  <div class="users-page">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-dropdown @command="handleImportExport">
          <el-button type="success">
            <el-icon><Download /></el-icon>
            导入导出
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="template">
                <el-icon><Document /></el-icon>
                下载Excel模板
              </el-dropdown-item>
              <el-dropdown-item command="import">
                <el-icon><Upload /></el-icon>
                导入用户
              </el-dropdown-item>
              <el-dropdown-item command="export">
                <el-icon><Download /></el-icon>
                导出Excel
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="addUser">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="搜索用户名、邮箱或姓名"
            clearable
            style="width: 300px;"
            @keyup.enter="loadUsers"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 120px;"
          >
            <el-option label="全部" :value="null" />
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadUsers">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card>
      <!-- 批量操作工具栏 -->
      <div class="table-toolbar" v-if="selectedUsers.length > 0">
        <span class="selected-info">已选择 {{ selectedUsers.length }} 个用户</span>
        <el-button
          type="danger"
          :icon="Delete"
          @click="showBatchDeleteDialog = true"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        :data="users"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :scroll-x="true"
      >
        <el-table-column type="selection" width="55" :selectable="isUserSelectable" />
        <el-table-column prop="username" label="用户名" width="120">
          <template #default="{ row }">
            <UserDisplay :user="row" />
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column label="姓名" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getFullName(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="is_active" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户组" width="150">
          <template #default="{ row }">
            <div v-if="row.user_groups && row.user_groups.length > 0">
              <el-tag
                v-for="group in row.user_groups"
                :key="group.id"
                size="small"
                style="margin-right: 4px; margin-bottom: 2px;"
              >
                {{ group.name }}
              </el-tag>
            </div>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="date_joined" label="创建时间">
          <template #default="{ row }">
            {{ row.date_joined ? new Date(row.date_joined).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  size="small"
                  type="primary"
                  :icon="Edit"
                  circle
                  @click="editUser(row)"
                />
              </el-tooltip>
              <el-tooltip content="查看权限" placement="top">
                <el-button
                  size="small"
                  type="info"
                  icon="View"
                  circle
                  @click="viewUserPermissions(row)"
                />
              </el-tooltip>
              <el-tooltip content="重置密码" placement="top">
                <el-button
                  size="small"
                  type="warning"
                  :icon="Key"
                  circle
                  @click="resetPassword(row)"
                />
              </el-tooltip>
              <el-tooltip :content="getStatusTooltip(row)" placement="top">
                <el-button
                  size="small"
                  :type="row.is_active ? 'danger' : 'success'"
                  :icon="row.is_active ? SwitchButton : Check"
                  :disabled="row.username === 'admin'"
                  circle
                  @click="toggleUserStatus(row)"
                />
              </el-tooltip>
              <el-tooltip :content="getDeleteTooltip(row)" placement="top">
                <el-button
                  size="small"
                  type="danger"
                  :icon="Delete"
                  :disabled="row.username === 'admin'"
                  circle
                  @click="deleteUser(row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="600px"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="!!editingUser" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="userForm.full_name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch v-model="userForm.is_active" active-text="激活" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="管理员">
          <el-switch v-model="userForm.is_staff" active-text="是" inactive-text="否" />
        </el-form-item>

        <!-- 高级权限设置 -->
        <el-divider content-position="left">
          <span style="color: #909399; font-size: 14px;">高级权限设置</span>
        </el-divider>
        <el-alert
          title="推荐通过用户组管理权限"
          type="info"
          :closable="false"
          style="margin-bottom: 15px;"
        >
          <template #default>
            建议通过用户组来管理用户权限，这样更便于批量管理和权限审计。
            <el-link type="primary" @click="showAdvancedPermissions = !showAdvancedPermissions">
              {{ showAdvancedPermissions ? '隐藏' : '显示' }}高级设置
            </el-link>
          </template>
        </el-alert>

        <div v-show="showAdvancedPermissions">
          <el-form-item label="用户组">
            <el-select v-model="userForm.user_group_ids" multiple placeholder="请选择用户组">
              <el-option
                v-for="group in userGroups"
                :key="group.id"
                :label="group.name"
                :value="group.id"
              />
            </el-select>
            <div class="form-tip">用户将继承所选用户组的角色权限</div>
          </el-form-item>
          <el-form-item label="直接角色">
            <el-select v-model="userForm.role_ids" multiple placeholder="请选择角色">
              <el-option
                v-for="role in roles"
                :key="role.id"
                :label="role.name"
                :value="role.id"
              />
            </el-select>
            <div class="form-tip">直接分配给用户的角色，仅在特殊情况下使用</div>
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="重置密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="passwordForm.new_password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="passwordForm.confirm_password" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword" :loading="resetting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量删除确认对话框 -->
    <el-dialog v-model="showBatchDeleteDialog" title="批量删除用户" width="500px">
      <div class="batch-delete-content">
        <el-alert
          title="警告"
          type="warning"
          description="此操作将永久删除选中的用户，无法恢复！"
          show-icon
          :closable="false"
        />
        <div class="delete-info">
          <p><strong>将要删除 {{ selectedUsers.length }} 个用户：</strong></p>
          <ul class="user-list">
            <li v-for="user in selectedUsers" :key="user.id">
              {{ user.username }} ({{ getFullName(user) }})
            </li>
          </ul>
        </div>
      </div>

      <template #footer>
        <el-button @click="showBatchDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmBatchDelete" :loading="batchDeleting">
          确认删除
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户菜单权限预览对话框 -->
    <el-dialog v-model="showPermissionsDialog" title="用户菜单权限详情" width="900px">
      <div v-loading="loadingPermissions">
        <div v-if="currentUserPermissions">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ currentUser?.username }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentUser?.email }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ getFullName(currentUser) }}</el-descriptions-item>
            <el-descriptions-item label="是否超级用户">
              <el-tag :type="currentUserPermissions.is_superuser ? 'success' : 'info'">
                {{ currentUserPermissions.is_superuser ? '是' : '否' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="left">菜单权限来源分析</el-divider>

          <!-- 直接分配的菜单权限 -->
          <div class="permission-section">
            <h4>
              <el-icon><User /></el-icon>
              直接分配的菜单权限 ({{ currentUserPermissions.direct_menus?.length || 0 }})
            </h4>
            <div v-if="currentUserPermissions.direct_menus?.length > 0">
              <div v-for="menu in currentUserPermissions.direct_menus" :key="menu.id" class="menu-item">
                <el-tag type="primary" style="margin: 2px;">
                  <el-icon v-if="menu.icon" style="margin-right: 4px;">
                    <component :is="menu.icon" />
                  </el-icon>
                  {{ menu.name }}
                </el-tag>
              </div>
            </div>
            <el-empty v-else description="无直接分配的菜单权限" :image-size="60" />
          </div>

          <!-- 用户组继承的菜单权限 -->
          <div class="permission-section">
            <h4>
              <el-icon><UserFilled /></el-icon>
              用户组继承的菜单权限
            </h4>
            <div v-if="Object.keys(currentUserPermissions.group_menus || {}).length > 0">
              <div v-for="(menus, groupName) in currentUserPermissions.group_menus" :key="groupName" class="group-permissions">
                <h5>
                  <el-icon><Collection /></el-icon>
                  {{ groupName }} ({{ menus.length }}个菜单)
                </h5>
                <div class="menu-list">
                  <div v-for="menu in menus" :key="menu.id" class="menu-item">
                    <el-tag type="success" style="margin: 2px;">
                      <el-icon v-if="menu.icon" style="margin-right: 4px;">
                        <component :is="menu.icon" />
                      </el-icon>
                      {{ menu.name }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="无用户组继承的菜单权限" :image-size="60" />
          </div>

          <!-- 所有菜单权限汇总 -->
          <div class="permission-section">
            <h4>
              <el-icon><Menu /></el-icon>
              所有菜单权限汇总 ({{ currentUserPermissions.all_menus?.length || 0 }})
            </h4>
            <div v-if="currentUserPermissions.all_menus?.length > 0">
              <div class="menu-grid">
                <div v-for="menu in currentUserPermissions.all_menus" :key="menu.id" class="menu-card">
                  <el-card shadow="hover" style="margin: 5px;">
                    <div class="menu-card-content">
                      <el-icon v-if="menu.icon" class="menu-icon">
                        <component :is="menu.icon" />
                      </el-icon>
                      <div class="menu-info">
                        <div class="menu-name">{{ menu.name }}</div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
            <el-empty v-else description="用户暂无任何菜单权限" :image-size="60" />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 导入用户对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入用户"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #default>
            <ul style="margin: 0; padding-left: 20px;">
              <li>请先下载Excel模板文件，按照模板格式填写用户信息</li>
              <li>用户名、邮箱、密码为必填项</li>
              <li>批量导入的用户默认为普通用户权限</li>
              <li>支持Excel(.xlsx/.xls)和CSV格式文件</li>
              <li>如果用户组或角色不存在，将使用默认值</li>
              <li>模板文件包含详细的填写说明，请仔细阅读</li>
            </ul>
          </template>
        </el-alert>

        <div class="upload-section">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".xlsx,.xls,.csv"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            drag
          >
            <el-icon class="el-icon--upload"><Upload /></el-icon>
            <div class="el-upload__text">
              将Excel或CSV文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持Excel(.xlsx/.xls)和CSV文件，文件大小不超过10MB
              </div>
            </template>
          </el-upload>
        </div>

        <div v-if="importResult" class="import-result">
          <el-alert
            :title="`导入完成：成功 ${importResult.success_count} 个，失败 ${importResult.error_count} 个`"
            :type="importResult.error_count > 0 ? 'warning' : 'success'"
            :closable="false"
            style="margin-bottom: 15px;"
          />

          <div v-if="importResult.errors && importResult.errors.length > 0">
            <h4>错误详情：</h4>
            <ul class="error-list">
              <li v-for="(error, index) in importResult.errors" :key="index" class="error-item">
                {{ error }}
              </li>
            </ul>
            <div v-if="importResult.total_errors > importResult.errors.length" class="more-errors">
              还有 {{ importResult.total_errors - importResult.errors.length }} 个错误未显示...
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button
            type="primary"
            :loading="importing"
            :disabled="!selectedFile"
            @click="handleImport"
          >
            {{ importing ? '导入中...' : '开始导入' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Key, Delete, Check, SwitchButton, User, UserFilled, Collection, Menu, House, Download, Upload, Document, ArrowDown } from '@element-plus/icons-vue'
import { userAPI } from '../../api/user'
import { userManagementAPI } from '../../api/userManagement'
import UserDisplay from '../../components/UserDisplay.vue'
import eventBus, { EVENT_NAMES } from '../../utils/eventBus'

const loading = ref(false)
const saving = ref(false)
const resetting = ref(false)
const batchDeleting = ref(false)
const showAddDialog = ref(false)
const showPasswordDialog = ref(false)
const showBatchDeleteDialog = ref(false)
const showPermissionsDialog = ref(false)
const showAdvancedPermissions = ref(false)
const showImportDialog = ref(false)
const editingUser = ref(null)
const resetPasswordUser = ref(null)
const currentUser = ref(null)
const currentUserPermissions = ref(null)
const loadingPermissions = ref(false)
const importing = ref(false)
const selectedFile = ref(null)
const importResult = ref(null)
const userFormRef = ref()
const passwordFormRef = ref()
const uploadRef = ref()
const selectedUsers = ref([])

const users = ref([])
const userGroups = ref([])
const roles = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

const searchForm = reactive({
  search: '',
  is_active: null
})

const userForm = reactive({
  username: '',
  email: '',
  full_name: '',
  phone: '',
  password: '',
  user_group_ids: [],
  role_ids: [],
  is_active: true,
  is_staff: false
})

const passwordForm = reactive({
  new_password: '',
  confirm_password: ''
})

// 检查用户名是否已存在的验证器
const validateUsername = async (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }

  // 如果是编辑模式且用户名未改变，跳过验证
  if (editingUser.value && editingUser.value.username === value) {
    callback()
    return
  }

  try {
    // 检查用户名是否已存在
    const response = await userAPI.getUsers({ search: value })
    const existingUser = response.results.find(user => user.username === value)
    if (existingUser) {
      callback(new Error('用户名已存在，请使用其他用户名'))
    } else {
      callback()
    }
  } catch (error) {
    // 如果检查失败，不阻止提交，让后端处理
    callback()
  }
}

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const passwordRules = {
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      ...searchForm
    }
    
    const response = await userAPI.getUsers(params)
    users.value = response.results || response
    total.value = response.count || users.value.length
  } catch (error) {
    console.error('加载用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadUserGroups = async () => {
  try {
    const response = await userAPI.getUserGroups()
    userGroups.value = response.results || response
  } catch (error) {
    console.error('加载用户组失败:', error)
  }
}

const loadRoles = async () => {
  try {
    const response = await userAPI.getRoles()
    roles.value = response.results || response
  } catch (error) {
    console.error('加载角色失败:', error)
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    search: '',
    is_active: null
  })
  loadUsers()
}

// 添加用户
const addUser = () => {
  editingUser.value = null
  Object.assign(userForm, {
    username: '',
    email: '',
    full_name: '',
    phone: '',
    password: '',
    user_group_ids: [],
    role_ids: [],
    is_active: true,
    is_staff: false
  })
  showAddDialog.value = true
}

// 获取完整姓名 - 直接使用 full_name 字段
const getFullName = (user) => {
  return user.full_name || '-'
}

// 删除姓名分割功能，直接使用完整姓名

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 批量删除确认
const confirmBatchDelete = async () => {
  if (selectedUsers.value.length === 0) return

  try {
    // 安全检查：防止删除当前登录用户
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    const hasCurrentUser = selectedUsers.value.some(user => user.id === currentUser.id)
    if (hasCurrentUser) {
      ElMessage.warning('选择的用户中包含当前登录用户，无法删除！')
      return
    }

    // 安全检查：防止删除admin用户
    const hasAdminUser = selectedUsers.value.some(user => user.username === 'admin')
    if (hasAdminUser) {
      await ElMessageBox.confirm(
        '🚨 严重警告：选择的用户中包含admin用户！\n\n删除admin用户将导致：\n• 永久失去系统管理权限\n• 无法恢复admin账户\n• 可能导致系统无法管理\n\n这是一个不可逆的危险操作！\n\n确定要继续吗？',
        '极度危险操作警告',
        {
          confirmButtonText: '我完全理解后果，继续删除',
          cancelButtonText: '取消',
          type: 'error',
          dangerouslyUseHTMLString: true
        }
      )
    }

    batchDeleting.value = true
    const userIds = selectedUsers.value.map(user => user.id)

    await userAPI.batchDeleteUsers(userIds)
    ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`)

    showBatchDeleteDialog.value = false
    selectedUsers.value = []
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除用户失败:', error)
      ElMessage.error('批量删除用户失败')
    }
  } finally {
    batchDeleting.value = false
  }
}

const editUser = (user) => {
  editingUser.value = user
  const fullName = getFullName(user)
  Object.assign(userForm, {
    username: user.username,
    email: user.email,
    full_name: fullName === '-' ? '' : fullName,
    phone: user.phone,
    password: '',
    user_group_ids: user.user_groups?.map(g => g.id) || [],
    role_ids: user.roles?.map(r => r.id) || [],
    is_active: user.is_active,
    is_staff: user.is_staff
  })
  showAddDialog.value = true
}

const saveUser = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()
    saving.value = true

    // 直接使用完整姓名，不进行分割
    const submitData = {
      ...userForm
      // 保留 full_name 字段
    }

    if (editingUser.value) {
      await userAPI.updateUser(editingUser.value.id, submitData)
      ElMessage.success('用户更新成功')
    } else {
      await userAPI.createUser(submitData)
      ElMessage.success('用户添加成功')
    }

    showAddDialog.value = false
    editingUser.value = null
    Object.assign(userForm, {
      username: '',
      email: '',
      full_name: '',
      phone: '',
      password: '',
      user_group_ids: [],
      role_ids: [],
      is_active: true,
      is_staff: false
    })
    loadUsers()
  } catch (error) {
    console.error('保存用户失败:', error)

    // 处理具体的错误信息
    if (error.response && error.response.data) {
      const errorData = error.response.data

      // 检查用户名重复错误
      if (errorData.username) {
        const usernameError = Array.isArray(errorData.username) ? errorData.username[0] : errorData.username
        if (usernameError.includes('已存在') || usernameError.includes('already exists') || usernameError.includes('unique')) {
          ElMessage.error('用户名已存在，请使用其他用户名')
        } else {
          ElMessage.error(`用户名错误: ${usernameError}`)
        }
      }
      // 检查邮箱重复错误
      else if (errorData.email) {
        const emailError = Array.isArray(errorData.email) ? errorData.email[0] : errorData.email
        if (emailError.includes('已存在') || emailError.includes('already exists') || emailError.includes('unique')) {
          ElMessage.error('邮箱地址已存在，请使用其他邮箱')
        } else {
          ElMessage.error(`邮箱错误: ${emailError}`)
        }
      }
      // 检查密码错误
      else if (errorData.password) {
        ElMessage.error(`密码错误: ${errorData.password[0] || '密码不符合要求'}`)
      }
      // 检查其他字段错误
      else if (errorData.non_field_errors) {
        ElMessage.error(errorData.non_field_errors[0])
      }
      // 通用错误处理
      else {
        const firstError = Object.values(errorData)[0]
        if (Array.isArray(firstError)) {
          ElMessage.error(firstError[0])
        } else {
          ElMessage.error(firstError || '保存失败，请检查输入信息')
        }
      }
    } else {
      ElMessage.error('保存失败，请稍后重试')
    }
  } finally {
    saving.value = false
  }
}

const viewUserPermissions = async (user) => {
  currentUser.value = user
  currentUserPermissions.value = null
  showPermissionsDialog.value = true

  loadingPermissions.value = true
  try {
    const response = await userAPI.getUserMenusDetail(user.id)
    currentUserPermissions.value = response
  } catch (error) {
    console.error('加载用户权限失败:', error)
    ElMessage.error('加载用户权限失败')
  } finally {
    loadingPermissions.value = false
  }
}

const resetPassword = (user) => {
  resetPasswordUser.value = user
  Object.assign(passwordForm, {
    new_password: '',
    confirm_password: ''
  })
  showPasswordDialog.value = true
}

const confirmResetPassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    resetting.value = true
    
    await userAPI.resetPassword(resetPasswordUser.value.id, passwordForm.new_password)
    ElMessage.success('密码重置成功')
    showPasswordDialog.value = false
    resetPasswordUser.value = null
  } catch (error) {
    console.error('重置密码失败:', error)
  } finally {
    resetting.value = false
  }
}

const toggleUserStatus = async (user) => {
  try {
    // 特殊检查：防止禁用当前登录用户
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    if (user.id === currentUser.id && user.is_active) {
      ElMessage.warning('不能禁用当前登录用户！')
      return
    }

    // 特殊检查：防止禁用admin用户
    if (user.username === 'admin' && user.is_active) {
      await ElMessageBox.confirm(
        '⚠️ 警告：您正在禁用admin用户！\n\n禁用admin用户可能导致：\n• 无法访问系统管理功能\n• 需要通过数据库手动恢复\n• 系统管理权限丢失\n\n确定要继续吗？',
        '危险操作警告',
        {
          confirmButtonText: '我了解风险，继续禁用',
          cancelButtonText: '取消',
          type: 'error',
          dangerouslyUseHTMLString: true
        }
      )
    } else {
      await ElMessageBox.confirm(
        `确定要${user.is_active ? '禁用' : '启用'}用户 "${user.username}" 吗？`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    }

    await userAPI.toggleUserStatus(user.id)
    ElMessage.success(`用户已${user.is_active ? '禁用' : '激活'}`)
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换用户状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const deleteUser = async (user) => {
  try {
    // 特殊检查：防止删除当前登录用户
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    if (user.id === currentUser.id) {
      ElMessage.warning('不能删除当前登录用户！')
      return
    }

    // 特殊检查：防止删除admin用户
    if (user.username === 'admin') {
      await ElMessageBox.confirm(
        '🚨 严重警告：您正在删除admin用户！\n\n删除admin用户将导致：\n• 永久失去系统管理权限\n• 无法恢复admin账户\n• 可能导致系统无法管理\n• 需要重新初始化数据库\n\n这是一个不可逆的危险操作！\n\n确定要继续吗？',
        '极度危险操作警告',
        {
          confirmButtonText: '我完全理解后果，删除admin',
          cancelButtonText: '取消',
          type: 'error',
          dangerouslyUseHTMLString: true
        }
      )
    } else {
      await ElMessageBox.confirm(
        `确定要删除用户 "${user.username}" 吗？\n\n删除后将无法恢复该用户的所有数据。`,
        '确认删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    }

    await userAPI.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 导入导出功能
const handleImportExport = (command) => {
  switch (command) {
    case 'template':
      downloadTemplate()
      break
    case 'import':
      openImportDialog()
      break
    case 'export':
      exportUsers()
      break
  }
}

const downloadTemplate = async () => {
  try {
    const response = await userManagementAPI.exportTemplate()
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'user_import_template.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('Excel模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

const openImportDialog = () => {
  showImportDialog.value = true
  selectedFile.value = null
  importResult.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const handleFileChange = (file) => {
  selectedFile.value = file.raw
  importResult.value = null
}

const handleFileRemove = () => {
  selectedFile.value = null
  importResult.value = null
}

const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  importing.value = true
  try {
    const response = await userManagementAPI.importUsers(selectedFile.value)
    importResult.value = response

    if (response.success_count > 0) {
      ElMessage.success(`成功导入 ${response.success_count} 个用户`)
      loadUsers() // 刷新用户列表
    }

    if (response.error_count > 0) {
      ElMessage.warning(`有 ${response.error_count} 个用户导入失败，请查看详情`)
    }
  } catch (error) {
    console.error('导入用户失败:', error)
    ElMessage.error(error.response?.data?.error || '导入用户失败')
  } finally {
    importing.value = false
  }
}

const exportUsers = async () => {
  try {
    const params = {
      ...searchForm
    }
    const response = await userManagementAPI.exportUsers(params)
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `users_export_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('用户数据Excel文件导出成功')
  } catch (error) {
    console.error('导出用户失败:', error)
    ElMessage.error('导出用户失败')
  }
}

// 获取状态切换按钮的工具提示文本
const getStatusTooltip = (user) => {
  if (user.username === 'admin') {
    return user.is_active ? 'admin用户不能禁用' : 'admin用户不能启用'
  }
  return user.is_active ? '禁用' : '启用'
}

// 获取删除按钮的工具提示文本
const getDeleteTooltip = (user) => {
  if (user.username === 'admin') {
    return 'admin用户不能删除'
  }
  return '删除'
}

// 判断用户是否可以被选择（用于批量操作）
const isUserSelectable = (row) => {
  return row.username !== 'admin'
}

// 处理用户信息更新事件
const handleUserProfileUpdate = (eventData) => {
  console.log('收到用户信息更新事件:', eventData)
  // 重新加载用户列表以获取最新数据
  loadUsers()
}

onMounted(() => {
  loadUsers()
  loadUserGroups()
  loadRoles()

  // 监听用户信息更新事件
  eventBus.on(EVENT_NAMES.USER_PROFILE_UPDATED, handleUserProfileUpdate)
})

onUnmounted(() => {
  // 清理事件监听
  eventBus.off(EVENT_NAMES.USER_PROFILE_UPDATED, handleUserProfileUpdate)
})
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.batch-delete-content {
  margin: 16px 0;
}

.delete-info {
  margin-top: 16px;
}

.user-list {
  max-height: 200px;
  overflow-y: auto;
  margin: 8px 0;
  padding: 0;
  list-style: none;
}

.user-list li {
  padding: 4px 0;
  border-bottom: 1px solid #ebeef5;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.permission-section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.permission-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.group-permissions {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.group-permissions h5 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.menu-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}



.menu-list {
  padding-left: 20px;
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.menu-card {
  min-height: 80px;
}

.menu-card-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.menu-icon {
  font-size: 24px;
  color: #409eff;
}

.menu-info {
  flex: 1;
}

.menu-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.permission-section h4 {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.import-content {
  padding: 10px 0;
}

.upload-section {
  margin: 20px 0;
}

.import-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.error-list {
  margin: 10px 0;
  padding-left: 20px;
  max-height: 200px;
  overflow-y: auto;
}

.error-item {
  color: #e74c3c;
  margin-bottom: 5px;
  font-size: 13px;
}

.more-errors {
  color: #f39c12;
  font-size: 12px;
  margin-top: 10px;
  font-style: italic;
}


</style>
